package config_controller

import (
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
	cd "pear-admin-layui-go/app/sys/config/domain"
	cs "pear-admin-layui-go/app/sys/config/service"
	"pear-admin-layui-go/framework/login_filter"
	fr "pear-admin-layui-go/framework/result"
	ft "pear-admin-layui-go/framework/table"
	"strconv"
	"time"
)

func EditPage(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	config := cs.EditPage(id)
	c.HTML(http.StatusOK, "sys/config/edit.html", gin.H{
		"config": config,
	})
}

func Enable(c *gin.Context) {
	var cer cd.ConfigEnableRequest
	_ = c.ShouldBind(&cer)
	user, _ := login_filter.GetCurrentUser(c)
	cer.UpdateBy = user.Id
	cer.UpdateName = user.Username
	cer.UpdateTime = time.Now().Unix()
	fr.Result(c, cs.Enable(&cer))
}

func AddPage(c *gin.Context) {
	c.HTML(http.StatusOK, "sys/config/add.html", gin.H{})
}

func Table(c *gin.Context) {
	var csr cd.ConfigSearchRequest
	_ = c.ShouldBind(&csr)
	table, count := cs.Table(&csr)
	configTable := make([]cd.ConfigTableResponse, len(table))
	for i, v := range table {
		configTable[i] = cd.ConfigTableResponse{
			Id:         v.Id,
			Name:       v.Name,
			Value:      v.Value,
			Remark:     v.Remark,
			Enable:     v.Enable,
			CreateTime: v.CreateTime,
			CreateName: v.CreateName,
			UpdateTime: v.UpdateTime,
			UpdateName: v.UpdateName,
		}
	}
	c.JSON(http.StatusOK, ft.TableResponse{
		Data:  configTable,
		Count: count,
	})
}

func Edit(c *gin.Context) {
	var cer cd.ConfigEditRequest
	_ = c.ShouldBind(&cer)
	user, _ := login_filter.GetCurrentUser(c)
	cer.UpdateBy = user.Id
	cer.UpdateName = user.Username
	cer.UpdateTime = time.Now().Unix()
	d := cs.Edit(&cer)
	fr.Result(c, d)
}

func Save(c *gin.Context) {
	var csr cd.ConfigSaveRequest
	_ = c.ShouldBind(&csr)
	user, _ := login_filter.GetCurrentUser(c)
	csr.CreateTime = time.Now().Unix()
	csr.CreateName = user.Username
	csr.CreateBy = user.Id
	_, err := cs.Save(&csr)
	if err != nil {
		r := fr.Error()
		r.Msg = err.Error()
		c.JSON(http.StatusOK, r)
	} else {
		c.JSON(http.StatusOK, fr.Ok())
	}

}

func Page(c *gin.Context) {
	c.HTML(http.StatusOK, "sys/config/config.html", gin.H{
		"enable": template.HTML("<input type=\"checkbox\" name=\"enable\" value=\"{{d.id}}\" lay-skin=\"switch\" lay-text=\"启用|禁用\" lay-filter=\"enable\" {{ d.enable == true ? 'checked' : '' }}/>"),
	})
}
